<template>
  <div class="w-full h-full bg-black text-white p-4 flex flex-col space-y-4 gap-2">
    <IInput v-model="search" placeholder="请输入关键字" clearable class="w-full max-w-sm" />
    <div v-if="treeData?.length === 0 || treeData === undefined" class="empty-placeholder">
      <template v-if="treeData?.length === 0">暂无数据</template>
      <template v-else>请先选择模块</template>
    </div>
    <el-tree
      v-else
      ref="treeRef"
      :data="treeData"
      :props="defaultProps"
      highlight-current
      :current-node-key="currentNodeKey"
      :filter-node-method="filterNode"
      @node-click="handleNodeClick"
      class="flex-1 overflow-auto rounded p-4"
      style="
        background-color: #3c3c3c;
        border: 2px solid #1c273a;
        box-shadow: 0 6px 20px rgba(255, 255, 255, 0.6);
        color: #ffffff;
      "
    >
      <template #default="{ node, data }">
        <span class="custom-tree">{{ data.label }}</span>
      </template>
    </el-tree>
  </div>
</template>

<script setup lang="ts">
import { onMounted, ref, watch } from 'vue'
import IInput from './UI/Input.vue'
import type { ElTree } from 'element-plus'
import {
  classifyByTopic,
  classifyByCreator,
  type DataItem,
  type TreeNode,
} from '@/utils/ClassifyService'

const search = ref('')
const currentNodeKey = ref<number | null>(null)

// ref获取 el-tree 组件实例
const treeRef = ref<InstanceType<typeof ElTree>>()

function handleNodeClick(node: any) {
  currentNodeKey.value = node.id
}

// 树数据，注意每个节点需要id
const treeData = ref([] as TreeNode[] | undefined)

const defaultProps = {
  children: 'children',
  label: 'label',
}

const props = defineProps<{
  data: DataItem[]
}>()

watch(props.data, (val) => {
  const classifyResult = classifyByTopic(val)
  if (classifyResult) {
    treeData.value = classifyResult
  }
})

// 输入时自动过滤
watch(search, (val) => {
  treeRef.value?.filter(val)
})

// 节点过滤方法
function filterNode(value: string, data: any) {
  if (!value) return true
  return data.label.includes(value)
}

onMounted(() => {
  const classifyResult = classifyByTopic(props.data)
  if (classifyResult) {
    treeData.value = classifyResult
  }else {
    treeData.value = undefined
  }
})
</script>

<style scoped>
:deep(.el-tree-node__content:hover) {
  background-color: #5a5a5a !important;
  color: #dae0e6 !important;
}

:deep(.el-tree-node.is-current, .el-tree-node.is-focusable) {
  background-color: #0d3c6b !important;
  color: #fff !important;
  font-weight: bold !important;
  box-shadow: 0 0 8px #1e90ff !important;
  .el-tree-node__content {
    background-color: #0d3c6b !important;
    color: #fff !important;
  }
}

.empty-placeholder {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #999;
  font-size: 14px;
  background-color: #2c2c2c;
  border: 3px solid #1c273a;
  border-radius: 8px;
  box-shadow: 0 6px 20px rgba(255, 255, 255, 0.6);
}

</style>
